package com.weiyuwqj.server.service.debt.impl;

import com.github.pagehelper.PageHelper;
import com.weiyuwqj.api.common.PageList;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.constant.Global;
import com.weiyuwqj.api.constant.ItemStatus;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.exception.HfException;
//import com.weiyuwqj.api.hengfeng.model.base.HfBaseResponseBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfDataBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.model.item.HfCommission;
//import com.weiyuwqj.api.hengfeng.model.item.HfItemTransferDebt;
//import com.weiyuwqj.api.hengfeng.model.platform.HfFundFreezeOrTraw;
//import com.weiyuwqj.api.hengfeng.param.HfDebtInvestParam;
import com.weiyuwqj.api.model.BasCoupon;
import com.weiyuwqj.api.model.BasDebt;
import com.weiyuwqj.api.model.BasItem;
import com.weiyuwqj.api.model.BasUser;
import com.weiyuwqj.api.model.BusDebtCollect;
import com.weiyuwqj.api.model.BusDebtInvest;
import com.weiyuwqj.api.model.BusItemCollect;
import com.weiyuwqj.api.model.BusItemInvest;
import com.weiyuwqj.api.model.vo.BasDebtVO;
import com.weiyuwqj.api.model.vo.BusDebtInvestVO;
import com.weiyuwqj.api.model.vo.DebtCollectStatVo;
import com.weiyuwqj.api.model.vo.DebtDetailVo;
import com.weiyuwqj.api.service.BasDebtService;
import com.weiyuwqj.api.service.ContractsGeneratorService;
import com.weiyuwqj.api.util.DateUtils;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.StringUtils;
import com.weiyuwqj.server.mapper.BasCouponMapper;
import com.weiyuwqj.server.mapper.BasDebtMapper;
import com.weiyuwqj.server.mapper.BasItemMapper;
import com.weiyuwqj.server.mapper.BasUserMapper;
import com.weiyuwqj.server.mapper.BusDebtCollectMapper;
import com.weiyuwqj.server.mapper.BusDebtInvestMapper;
import com.weiyuwqj.server.mapper.BusItemCollectMapper;
import com.weiyuwqj.server.mapper.BusItemInvestMapper;
import com.weiyuwqj.server.mapper.BusItemRepayMapper;
//import com.weiyuwqj.server.pay.InvestApi;
//import com.weiyuwqj.server.pay.PlatformApi;
import com.weiyuwqj.server.service.account.module.DealAction;
import com.weiyuwqj.server.service.account.module.DealModule;
import com.weiyuwqj.server.service.account.module.action.debt.DebtInvestFeeDealAction;
import com.weiyuwqj.server.service.account.module.action.debt.DebtInvestFreezeDealAction;
import com.weiyuwqj.server.service.account.module.action.debt.DebtInvestWaitDealAction;
import com.weiyuwqj.server.service.account.module.action.debt.DebtLoanUsableDealAction;
import com.weiyuwqj.server.service.account.module.action.debt.DebtLoanWaitDealAction;
import com.weiyuwqj.server.service.account.module.action.debt.DebtPlatformFeeDealAction;
import com.weiyuwqj.server.service.account.module.action.debt.DebtRecallDealAction;
import com.weiyuwqj.server.service.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyong on 2017/3/22.
 */
@Service("debtService")
public class BasDebtServiceImpl extends BaseServiceImpl<BasDebt> implements BasDebtService {

    @Autowired
    private BasDebtMapper debtMapper;
    @Autowired
    private BusDebtInvestMapper debtInvestMapper;
    @Autowired
    private BusItemCollectMapper itemCollectMapper;
    @Autowired
    private BusDebtCollectMapper debtCollectMapper;
    @Autowired
    private BusItemInvestMapper itemInvestMapper;
    @Autowired
    private DealModule dealModule;
    @Autowired
    private BasUserMapper userMapper;
    @Autowired
    private BasItemMapper itemMapper;

    @Autowired
    private BasCouponMapper couponMapper;

    @Autowired
    private BusItemRepayMapper itemRepayMapper;

	@Autowired
	private ContractsGeneratorService contractsGeneratorService;

//    @Autowired
//    private InvestApi investApi;
//    @Autowired
//    private PlatformApi platformApi;

    /**
     * 添加债权
     *
     * @param debt 债权对象
     * @return 添加结果
     */
    @Override
    public Integer addDebt(BasDebt debt) {
        debt.setAddtime(new Date());
        debt.setDebtScale(BigDecimal.ZERO);
        debt.setOngoingAmount(BigDecimal.ZERO);
        debt.setStatus(0);
        Integer itemId = 0;
        BigDecimal investAmount = BigDecimal.ZERO;
        //判断来源，是投资表过来的
        if (null != debt.getInvestId()) {
            //查询投资表
            BusItemInvest itemInvest = itemInvestMapper.selectByPrimaryKey(debt.getInvestId());

            //获取当前时间与投资时间的相差天数
            Integer days = DateUtils.daysOfTwo(itemInvest.getAddtime(), new Date());
            Integer lockDay = Integer.parseInt(Global.getDebtBeginLockDay());
            if(days<lockDay){
                throw new CrowdException("debt.invest_date_lock");
            }

            //查询这笔投资记录是否发布债转
            BasDebt basDebt = debtMapper.getDebtByInvestIdOrDebtInvestId(debt.getInvestId(), null);
            if(basDebt != null){
                throw new CrowdException("debt.debt_exists");
            }

            //统计未还款的待收总本金
            Map map = new HashMap();
            map.put("investId",debt.getInvestId());
            DebtCollectStatVo collectStatVo = itemCollectMapper.statNoPayCollect(map);

            itemId = itemInvest.getItemId();
            debt.setItemId(itemInvest.getItemId());
            debt.setAmount(collectStatVo.getCollectPrincipal());
            debt.setUserId(itemInvest.getUserId());
            debt.setRestPeriods(itemCollectMapper.getCollectListNotOverCount(debt.getInvestId())); // 设置剩余期数
            debt.setRepayIncome(itemRepayMapper.getRepayIncome(itemId)); // 预计收益
            debt.setRepayEndDate(itemRepayMapper.getRepayEndDate(itemId)); // 回款日期
            investAmount = itemInvest.getInvestDealAmount();
            //查询投资人是个人还是企业
            BasUser user = userMapper.selectByPrimaryKey(itemInvest.getUserId());
            if (user.getType() == 1 || user.getType() == 2) {
                debt.setType(1);
            } else if (user.getType() == 4 || user.getType() == 3) {
                debt.setType(2);
            }

            //判断是否能创建债权
            if (itemInvest.getDebtTransferStatus() == 1) {
                throw new CrowdException("debt_published");
            }
            //修改投资状态
            int count = itemInvestMapper.modifyDebtInvestStatusById(1, 0, itemInvest.getId());
            if (count < 1) {
                throw new CrowdException("update_error");
            }
        } else if (null != debt.getDebtInvestId()) {//判断来源，是债权投资表过来的
            //查询债权投资表
            BusDebtInvest debtInvest = debtInvestMapper.selectByPrimaryKey(debt.getDebtInvestId());

            //获取当前时间与投资时间的相差天数
            Integer days = DateUtils.daysOfTwo(debtInvest.getAddtime(), new Date());
            Integer lockDay = Integer.parseInt(Global.getDebtBeginLockDay());
            if(days<lockDay){
                throw new CrowdException("debt.invest_date_lock");
            }

            //查询这笔投资记录是否发布债转
            BasDebt basDebt = debtMapper.getDebtByInvestIdOrDebtInvestId(null, debt.getDebtInvestId());
            if(basDebt != null){
                throw new CrowdException("debt.debt_exists");
            }

            //统计未还款的待收总本金
            Map map = new HashMap();
            map.put("investId",debt.getDebtInvestId());
            DebtCollectStatVo collectStatVo = debtCollectMapper.statNoPayCollect(map);

            itemId = debtInvest.getItemId(); // 项目ID
            debt.setItemId(debtInvest.getItemId());
            debt.setAmount(collectStatVo.getCollectPrincipal());
            debt.setUserId(debtInvest.getInvestUserId());
            debt.setRestPeriods(debtCollectMapper.getCollectListNotOverCount(debt.getDebtInvestId())); // 设置剩余期数
            debt.setRepayIncome(itemRepayMapper.getRepayIncome(itemId)); // 预计收益
            debt.setRepayEndDate(itemRepayMapper.getRepayEndDate(itemId)); // 回款日期
            investAmount = debtInvest.getInvestAmount();
            //查询投资人是个人还是企业
            BasUser user = userMapper.selectByPrimaryKey(debtInvest.getInvestUserId());
            if (user.getType() == 1 || user.getType() == 2) {
                debt.setType(1);
            } else if (user.getType() == 4 || user.getType() == 3) {
                debt.setType(2);
            }
            //判断是否能创建债权
            if (debtInvest.getStatus() == 1) {
                throw new CrowdException("debt_published");
            }
            //修改投资状态
            int count = debtInvestMapper.modifyDebtInvestStatusById(1, 0, debtInvest.getId());
            if (count < 1) {
                throw new CrowdException("update_error");
            }
        }
        BasItem item = itemMapper.selectByPrimaryKey(itemId);
        if (item == null || item.getItemStatus() != ItemStatus.REPAYING) {
            throw new CrowdException("item.status_is_not_correct");
        }
        //计算手续费
        BigDecimal fee = item.getDebtServeFeeRate().multiply(investAmount).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
        debt.setFee(fee);
        debtMapper.insert(debt);
//        autoInvest.basDebtMatchingAutoRule(debt);
        return 1;
    }

//    /**
//     * 查询债权列表
//     *
//     * @param p   分页参数
//     * @param map 债权对象
//     * @return 债权列表
//     */
//    @Override
//    public PageList debtList(Paginator p, Map map) {
//        PageHelper.startPage(p.getPageNum(), p.getPageSize());
//        List<BasDebtVO> list = debtMapper.getDebtList(map);
//        //债权撤回
//        debtRecall(list);
//        return new PageList(list);
//    }

//    /**
//     * 债权撤回
//     *
//     * @param list 债权列表
//     */
//    private void debtRecall(List<BasDebtVO> list) {
//        //循环判断是否在有效期内
//        for (BasDebtVO debtVO : list) {
//            //添加时间
//            Long addtime = debtVO.getAddtime().getTime();
//            //有效时间
//            Long effective = debtVO.getEndDays().longValue() * 24 * 60 * 60 * 1000;
//            //当前时间
//            Long nowDate = new Date().getTime();
//            if ((addtime + effective) < nowDate) {
//                HfDebtInvestParam debtInvestParam = new HfDebtInvestParam();
//                debtInvestParam.setDebtId(debtVO.getId());
//                List<BusDebtInvestVO> debtInvestList = debtInvestMapper.getDebtInvestList(debtInvestParam);
//                for (BusDebtInvestVO debtInvestVO : debtInvestList) {
//
//                    //解冻投资人资金
//                    BasCoupon coupon = couponMapper.getCouponByDebtInvestId(debtInvestVO.getId());
//                    HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//                    if (null != coupon) {
//                        freezeOrTraw.setAmount(debtInvestVO.getInvestAmount().subtract(coupon.getAmount()).toString());
//                    } else {
//                        freezeOrTraw.setAmount(debtInvestVO.getInvestAmount().toString());
//                    }
//                    freezeOrTraw.setFreeze_flg("02");
//                    freezeOrTraw.setPlatcust(userMapper.selectByPrimaryKey(debtInvestVO.getInvestUserId()).getPlatformId());
//                    freezeOrTraw.setRemark(debtInvestVO.getInvestUserId() + "解除冻结");
//                    freezeOrTraw.setOrder_no(StringUtils.getOrderNo());
//                    freezeOrTraw.setFreeze_order_no(debtInvestVO.getFreezeOrderNo());
//	                try {
//		                HfResultBean result = platformApi.doFundFreeze(freezeOrTraw); // 请求恒丰
//	                } catch (Exception e) {
//		                return;
//                    }
//                    //撤回投资债权人的资金
//                    DealAction debtRecallDealAction = new DebtRecallDealAction();
//                    debtRecallDealAction.deal(debtInvestVO.getInvestUserId(), debtInvestVO.getInvestAmount(), "撤回投资债权人投资金额");
//                    dealModule.dealAction(debtRecallDealAction);
//                    //修改投资状态为已过期
//                    debtInvestMapper.modifyDebtInvestStatusById(2, 0, debtInvestVO.getId());
//
//                }
//                //修改债权状态为已过期
//                debtMapper.modifyDebtStatusById(2, 0, debtVO.getId());
//            }
//            if (null != debtVO.getInvestId()) {
//                //修改投资状态
//                itemInvestMapper.modifyDebtInvestStatusById(0, 1, debtVO.getInvestId());
//            } else if (null != debtVO.getDebtInvestId()) {
//                //修改投资状态
//                debtInvestMapper.modifyDebtInvestStatusById(0, 1, debtVO.getDebtInvestId());
//            }
//        }
//    }

//    /**
//     * 债权回调成功
//     *
//     * @param debtId
//     */
//    @Override
//    public void debtCheckSuccess(Integer debtId) {
//        //查找债权的记录
//        BasDebtVO debtVO = debtMapper.getDebtById(debtId);
//        //查找债权投资记录
//        HfDebtInvestParam debtInvestParam = new HfDebtInvestParam();
//        debtInvestParam.setDebtId(debtId);
//        List<BusDebtInvestVO> debtInvestVOs = debtInvestMapper.getDebtInvestList(debtInvestParam);
//
//        BasUser basUser = userMapper.selectByPrimaryKey(debtVO.getUserId());
//        BasItem basItem = itemMapper.selectByPrimaryKey(debtVO.getItemId());
//
//        //债权人待收金额
//        BigDecimal wailTotal = BigDecimal.ZERO;
//        //总本金
//        BigDecimal capitalTotal = BigDecimal.ZERO;
//        //总服务费
//        BigDecimal totalPayoutAmt = BigDecimal.ZERO;
//
//        for (int i = 0; i < debtInvestVOs.size(); i++) {
//            BusDebtInvestVO debtInvestVO = debtInvestVOs.get(i);
//
//            //计算投资金额占总金额的百分比,精确到4位
//            BigDecimal investScale = debtInvestVO.getInvestAmount().divide(debtVO.getAmount(), 4, BigDecimal.ROUND_HALF_UP);
//            //前几期需要还的总额
//            BigDecimal amountTotal = BigDecimal.ZERO;
//            BigDecimal interestTotal = BigDecimal.ZERO;
//            BigDecimal principalTotal = BigDecimal.ZERO;
//            //债权来源是投资表
//            BasUser user = userMapper.selectByPrimaryKey(debtInvestVO.getInvestUserId());
//            if (null != debtVO.getInvestId() && 0 != debtVO.getInvestId()) {
//                //根据投资id查询未债权的待收列表
//                List<BusItemCollect> collectList = itemCollectMapper.getCollectListByInvestId(debtVO.getInvestId());
//
//                for (BusItemCollect itemCollect : collectList) {
//                    //本期总额
//                    BigDecimal amount = itemCollect.getCollectAmount().multiply(investScale).divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//                    //本期利息
//                    BigDecimal interest = itemCollect.getCollectInterest().multiply(investScale).divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//                    //本期本金
//                    BigDecimal principal = itemCollect.getCollectPrincipal().multiply(investScale).divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//                    //插入债权待收表
//                    BusDebtCollect debtCollect = new BusDebtCollect();
//                    //判断是否是最后一期,
////                    if (itemCollect.getCollectCurrentPeriod() == itemCollect.getCollectTotalPeriod()) {
////                        debtCollect.setCollectAmount(itemCollect.getCollectAmount().subtract(amountTotal));
////                        debtCollect.setCollectInterest(itemCollect.getCollectInterest().subtract(interestTotal));
////                        debtCollect.setCollectPrincipal(itemCollect.getCollectPrincipal().subtract(principalTotal));
////                    } else {
//                    debtCollect.setCollectAmount(amount);
//                    debtCollect.setCollectInterest(interest);
//                    debtCollect.setCollectPrincipal(principal);
////                    }
//                    debtCollect.setActualCollectAmount(BigDecimal.ZERO);
//                    debtCollect.setActualCollectInterest(BigDecimal.ZERO);
//                    debtCollect.setActualCollectPrincipal(BigDecimal.ZERO);
//                    debtCollect.setCollectStatus(0);
//                    debtCollect.setDebtId(debtVO.getId());
//                    debtCollect.setDebtUserId(debtInvestVO.getInvestUserId());
//                    debtCollect.setDebtInvestId(debtInvestVO.getId());
//                    debtCollect.setDebtTransferStatus(0);
//                    debtCollect.setItemId(debtVO.getItemId());
//                    debtCollect.setInvestId(debtVO.getInvestId());
//                    debtCollect.setCollectCurrentPeriod(itemCollect.getCollectCurrentPeriod());
//                    debtCollect.setCollectTotalPeriod(itemCollect.getCollectTotalPeriod());
//                    debtCollect.setAddip(IpUtils.get());
//                    debtCollect.setAdditionalRateAmount(BigDecimal.ZERO);
//                    debtCollect.setAddtime(new Date());
//                    debtCollect.setCollectTime(itemCollect.getCollectTime());
//                    debtCollect.setCollectId(itemCollect.getId());
//                    debtCollect.setDebtCollectId(0);
//                    debtCollect.setPlatformId(user.getPlatformId());
//                    debtCollectMapper.insert(debtCollect);
//
//                    //累计总额，累计利息，累计本金
//                    amountTotal = amountTotal.add(amount);
//                    interestTotal = interestTotal.add(interest);
//                    principalTotal = principalTotal.add(principal);
//
//                }
//                //判断是否是投资的最后一笔，是的话处理之前的collect表
//                //并修改投资表的是否已债权
//                if (i == debtInvestVOs.size() - 1) {
//                    for (BusItemCollect itemCollect : collectList) {
//                        itemCollectMapper.modifyDebtCollectStatusById(1, 0, itemCollect.getId());
//                    }
//                    itemInvestMapper.modifyDebtInvestStatusById(1, 0, debtVO.getInvestId());
//                }
//
//                //解冻投资人资金
//                BasCoupon coupon = couponMapper.getCouponByDebtInvestId(debtInvestVO.getId());
//                HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//                if (null != coupon) {
//                    freezeOrTraw.setAmount(debtInvestVO.getInvestAmount().subtract(coupon.getAmount()).toString());
//                } else {
//                    freezeOrTraw.setAmount(debtInvestVO.getInvestAmount().toString());
//                }
//                freezeOrTraw.setFreeze_flg("02");
//                freezeOrTraw.setPlatcust(user.getPlatformId());
//                freezeOrTraw.setRemark(debtInvestVO.getInvestUserId() + "解除冻结");
//                freezeOrTraw.setOrder_no(StringUtils.getOrderNo());
//                freezeOrTraw.setFreeze_order_no(debtInvestVO.getFreezeOrderNo());
//	            HfResultBean result = platformApi.doFundFreeze(freezeOrTraw);  // 请求恒丰
//	            //if (!result.isSuccess()) { // 成功订单数量为0则抛出异常
//	            //   throw new HfException("HfException", result.getMessageText());
//	            //}
//
//                BigDecimal payoutAmt = basItem.getDebtServeFeeRate().multiply(debtInvestVO.getInvestAmount()).
//                        divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
//                BigDecimal transAmt = payoutAmt.add(debtInvestVO.getInvestAmount());
//                totalPayoutAmt = totalPayoutAmt.add(payoutAmt);
//                HfItemTransferDebt transferDebt = new HfItemTransferDebt();
//                transferDebt.setPlatcust(basUser.getPlatformId());
//                transferDebt.setCoupon_amt("0");
//                transferDebt.setOrder_no(debtInvestVO.getInvestOrder());
//                transferDebt.setTrans_share("1");
//                transferDebt.setProd_id(debtVO.getItemId().toString());
//                transferDebt.setTrans_amt(transAmt.toString());
//                transferDebt.setCoupon_amt("0");
//	            transferDebt.setDeal_platcust(user.getPlatformId());
//	            transferDebt.setDeal_amount(debtInvestVO.getInvestAmount().toString());
//                transferDebt.setTransfer_income("0");
//                transferDebt.setPublish_date(DateUtils.formatDate(debtVO.getAddtime(), "yyyy-MM-dd HH:mm:ss"));
//                transferDebt.setTrans_date(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
//                transferDebt.setRelated_prod_ids(debtVO.getItemId().toString());
//                HfCommission commission = new HfCommission();
//                commission.setPayout_amt(payoutAmt.toString());
//                commission.setPayout_plat_type("01"); //01-自有 11-垫付
//                transferDebt.setCommission(commission);
//                transferDebt.setIncome_acct("11");
//                HfResultBean resultBean = investApi.transferDebt(transferDebt);
//                if (!resultBean.isSuccess()) {
//                    throw new HfException("HfException", resultBean.getMessageText());
//                }
//	            //HfResultBean result1 = HfResultBean.getBeanBySingle(responseBean1);
//	            //if (!result1.isSuccess()) {
//	            //   throw new HfException("HfException", result.getMessageText());
//	            //}
//	            // todo 普通标合同生成
//	            contractsGeneratorService.generateContractsByItem(basUser.getId(), user.getId(), debtVO.getInvestId().toString(), debtInvestVO.getInvestOrder());
//            } else if (null != debtVO.getDebtInvestId() && debtVO.getDebtInvestId() != 0) {//债权来源债权投资表
//                //查询上次需债转的债转投资记录
//                BusDebtInvest debtInvest = debtInvestMapper.selectByPrimaryKey(debtVO.getDebtInvestId());
//                //查询债权待收列表
//                List<BusDebtCollect> debtCollectList = debtCollectMapper.getDebtCollectListByDebtInvestId(debtVO.getDebtInvestId());
//                for (BusDebtCollect debtCollect : debtCollectList) {
//                    //本期总额
//                    BigDecimal amount = debtCollect.getCollectAmount().multiply(investScale).divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//                    //本期利息
//                    BigDecimal interest = debtCollect.getCollectInterest().multiply(investScale).divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//                    //本期本金
//                    BigDecimal principal = debtCollect.getCollectPrincipal().multiply(investScale).divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//                    //插入债权待收表
//                    BusDebtCollect busDebtCollect = new BusDebtCollect();
//                    //判断是否是最后一期,
////                    if (debtCollect.getCollectCurrentPeriod() == debtCollect.getCollectTotalPeriod()) {
////                        busDebtCollect.setCollectAmount(debtCollect.getCollectAmount().subtract(amountTotal));
////                        busDebtCollect.setCollectInterest(debtCollect.getCollectInterest().subtract(interestTotal));
////                        busDebtCollect.setCollectPrincipal(debtCollect.getCollectPrincipal().subtract(principalTotal));
////                    } else {
//                    busDebtCollect.setCollectAmount(amount);
//                    busDebtCollect.setCollectInterest(interest);
//                    busDebtCollect.setCollectPrincipal(principal);
////                    }
//                    busDebtCollect.setActualCollectAmount(BigDecimal.ZERO);
//                    busDebtCollect.setActualCollectInterest(BigDecimal.ZERO);
//                    busDebtCollect.setActualCollectPrincipal(BigDecimal.ZERO);
//                    busDebtCollect.setCollectStatus(0);
//                    busDebtCollect.setDebtId(debtVO.getId());
//                    busDebtCollect.setDebtUserId(debtInvestVO.getInvestUserId());
//                    busDebtCollect.setDebtInvestId(debtInvestVO.getId());
//                    busDebtCollect.setDebtTransferStatus(0);
//                    busDebtCollect.setItemId(debtVO.getItemId());
//                    busDebtCollect.setInvestId(debtInvest.getInvestId());
//                    busDebtCollect.setCollectCurrentPeriod(debtCollect.getCollectCurrentPeriod());
//                    busDebtCollect.setCollectTotalPeriod(debtCollect.getCollectTotalPeriod());
//                    busDebtCollect.setAddip(IpUtils.get());
//                    busDebtCollect.setAdditionalRateAmount(BigDecimal.ZERO);
//                    busDebtCollect.setAddtime(new Date());
//                    busDebtCollect.setDebtCollectId(debtCollect.getId());
//                    busDebtCollect.setCollectId(0);
//                    busDebtCollect.setCollectTime(debtCollect.getCollectTime());
//                    busDebtCollect.setPlatformId(user.getPlatformId());
//                    debtCollectMapper.insert(busDebtCollect);
//
//                    //累计总额，累计利息，累计本金
//                    amountTotal = amountTotal.add(amount);
//                    interestTotal = interestTotal.add(interest);
//                    principalTotal = principalTotal.add(principal);
//                }
//
//                //判断是否是投资的最后一笔，是的话处理之前的collect表
//                //并修改投资表的是否已债权
//                if (i == debtInvestVOs.size() - 1) {
//                    for (BusDebtCollect debtCollect : debtCollectList) {
//                        debtCollectMapper.modifyDebtCollectStatusById(1, 0, debtCollect.getId());
//                    }
//                    debtInvestMapper.modifyDebtInvestStatusById(1, 0, debtVO.getDebtInvestId());
//                }
//
//                //解冻投资人资金
//                BasCoupon coupon = couponMapper.getCouponByDebtInvestId(debtInvestVO.getId());
//                HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//                if (null != coupon) {
//                    freezeOrTraw.setAmount(debtInvestVO.getInvestAmount().subtract(coupon.getAmount()).toString());
//                } else {
//                    freezeOrTraw.setAmount(debtInvestVO.getInvestAmount().toString());
//                }
//                freezeOrTraw.setFreeze_flg("02");
//                freezeOrTraw.setPlatcust(user.getPlatformId());
//                freezeOrTraw.setRemark(debtInvestVO.getInvestUserId() + "解除冻结");
//                freezeOrTraw.setOrder_no(StringUtils.getOrderNo());
//                freezeOrTraw.setFreeze_order_no(debtInvestVO.getFreezeOrderNo());
//	            HfResultBean result = platformApi.doFundFreeze(freezeOrTraw); // 请求恒丰
//	            //if (!result.isSuccess()) { // 成功订单数量为0则抛出异常
//	            //   throw new HfException("HfException", result.getMessageText());
//	            //}
//
//	            // todo 普通标合同生成
//	            contractsGeneratorService.generateContractsByItem(user.getId(), basItem.getId(), debtVO.getDebtInvestId().toString(), debtInvestVO.getInvestOrder());
//	            BigDecimal payoutAmt = basItem.getDebtServeFeeRate().multiply(debtInvestVO.getInvestAmount()).
//                        divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
//                BigDecimal transAmt = payoutAmt.add(debtInvestVO.getInvestAmount());
//                totalPayoutAmt = totalPayoutAmt.add(payoutAmt);
//
//                HfItemTransferDebt transferDebt = new HfItemTransferDebt();
//                transferDebt.setPlatcust(basUser.getPlatformId());
//                transferDebt.setCoupon_amt("0");
//                transferDebt.setOrder_no(debtInvestVO.getInvestOrder());
//                transferDebt.setTrans_share("1");
//                transferDebt.setProd_id(debtVO.getItemId().toString());
//                transferDebt.setTrans_amt(transAmt.toString());
//                transferDebt.setCoupon_amt("0");
//	            transferDebt.setDeal_platcust(user.getPlatformId());
//	            transferDebt.setDeal_amount(debtInvestVO.getInvestAmount().toString());
//                transferDebt.setTransfer_income("0");
//                transferDebt.setPublish_date(DateUtils.formatDate(debtVO.getAddtime(), "yyyy-MM-dd HH:mm:ss"));
//                transferDebt.setTrans_date(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
//                transferDebt.setRelated_prod_ids(debtVO.getItemId().toString());
//                HfCommission commission = new HfCommission();
//                commission.setPayout_amt(payoutAmt.toString());
//                commission.setPayout_plat_type("01");
//                transferDebt.setCommission(commission);
//                transferDebt.setIncome_acct("11"); //01-自有 11-垫付
//	            HfResultBean resultBean = investApi.transferDebt(transferDebt);
//	            if (!resultBean.isSuccess()) {
//		            throw new HfException("HfException", resultBean.getMessageText());
//	            }
//            }
//            //扣除投资债权人的凍結，增加待收
//            //扣除冻结
//            DealAction debtFreeze = new DebtInvestFreezeDealAction();
//            debtFreeze.deal(debtInvestVO.getInvestUserId(), debtInvestVO.getInvestAmount(), "扣除投资债权人冻结金额");
//            dealModule.dealAction(debtFreeze);
//            //产生待收
//            DealAction debtWait = new DebtInvestWaitDealAction();
//            debtWait.deal(debtInvestVO.getInvestUserId(), amountTotal, "产生投资债权人待收金额");
//            dealModule.dealAction(debtWait);
//            //总待收
//            wailTotal = wailTotal.add(amountTotal);
//            capitalTotal = capitalTotal.add(principalTotal);
//        }
//        //扣除发布债权人的待收，增加可用可提金额
//        DealAction debtLoanWait = new DebtLoanWaitDealAction();
//        debtLoanWait.deal(debtVO.getUserId(), wailTotal, "扣除债权人待收金额");
//        dealModule.dealAction(debtLoanWait);
//
//        DealAction debtLoanUsable = new DebtLoanUsableDealAction();
//        debtLoanUsable.deal(debtVO.getUserId(), capitalTotal, "产生债权人可用，可提");
//        dealModule.dealAction(debtLoanUsable);
//
//        //支付手续费
//        DealAction debtInvestFee = new DebtInvestFeeDealAction();
//        debtInvestFee.deal(debtVO.getUserId(), totalPayoutAmt, "债权人支付手续费");
//        dealModule.dealAction(debtInvestFee);
//        //平台收取手续费
//        DealAction debtPlatformFee = new DebtPlatformFeeDealAction();
//        debtPlatformFee.deal(Integer.parseInt(Global.getChargeAccountId()), totalPayoutAmt, "平台收取手续费");
//        dealModule.dealAction(debtPlatformFee);
//    }

    /**
     * 根据债权id查询债权对象
     *
     * @param debtId 债权ID
     * @return 债权详情
     */
    @Override
    public BasDebtVO getDebtById(Integer debtId) {
        return debtMapper.getDebtById(debtId);
    }

    /**
     * 根据投资id查询详情
     * @param investId
     * @return
     */
    @Override
    public DebtDetailVo getInvestByInvestId(Integer investId) {
        DebtDetailVo debtDetailVo = itemInvestMapper.getInvestByInvestId(investId);
        //剩余期限
        BusItemCollect itemCollect = itemCollectMapper.getCollectByInvestId(investId);
        Integer days = DateUtils.daysOfTwo(new Date(),itemCollect.getCollectTime());
        debtDetailVo.setLastDays(days);
        //剩余金额
        Map map = new HashMap();
        map.put("investId",investId);
        DebtCollectStatVo collectStatVo = itemCollectMapper.statNoPayCollect(map);
        debtDetailVo.setLastAmount(collectStatVo.getCollectPrincipal());
        //费用
        BigDecimal fee = debtDetailVo.getDebtServeFeeRate().multiply(collectStatVo.getCollectPrincipal()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
        debtDetailVo.setFee(fee);
        return debtDetailVo;
    }

    /**
     * 根据债权id查询信息
     * @param debtInvestId
     * @return
     */
    @Override
    public DebtDetailVo getDebtInvestByDebtInvestId(Integer debtInvestId) {
        DebtDetailVo debtDetailVo = debtInvestMapper.getDebtInvestByDebtInvestId(debtInvestId);
        //剩余期限
        BusDebtCollect itemCollect = debtCollectMapper.getCollectByDebtInvestId(debtInvestId);
        Integer days = DateUtils.daysOfTwo(new Date(),itemCollect.getCollectTime());
        debtDetailVo.setLastDays(days);
        //剩余金额
        Map map = new HashMap();
        map.put("investId",debtInvestId);
        DebtCollectStatVo collectStatVo = debtCollectMapper.statNoPayCollect(map);
        debtDetailVo.setLastAmount(collectStatVo.getCollectPrincipal());
        //费用
        BigDecimal fee = debtDetailVo.getDebtServeFeeRate().multiply(collectStatVo.getCollectPrincipal()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
        debtDetailVo.setFee(fee);
        return debtDetailVo;
    }

}
